package com.leinao.login.controller;

import com.leinao.commons.Response;
import com.leinao.config.EnvironmentConfig;
import com.leinao.config.RedisCacheConfig;
import com.leinao.constant.Constant;
import com.leinao.constant.LoginEnum;
import com.leinao.constant.ParameterEnum;
import com.leinao.login.service.LoginService;
import com.leinao.util.IpUtil;
import com.leinao.util.regex.RegexUtils;
import com.leinao.util.sha.RSAUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletRequest;
import java.net.UnknownHostException;

/**
 * 
 * 登录入口Controller
 * @author  wangshoufa 
 * @date 2018年11月15日 上午11:18:18
 *
 */
@RestController
@CrossOrigin
public class LoginController {
	Logger logger  = LoggerFactory.getLogger(LoginController.class);
	
	@Autowired
	LoginService loginService;
	
	@Autowired
	EnvironmentConfig env;
	
	@Autowired
	RedisCacheConfig redisCacheConfig;
	
	@PostMapping("/login")
	@ApiOperation(value="登录", notes="用户登录")
	public Response<Object> login(HttpServletRequest request,
			@ApiParam(value = "用户名", required = true) @RequestParam(required = true) String username,
			@ApiParam(value = "用户名", required = true) @RequestParam(required = true) String password)
			throws UnknownHostException {
		logger.info("clientIp is: {} ,username: {}", IpUtil.getClientIp(request), username);
		logger.info("serverIp is: {}", IpUtil.getCurrentIp());
		if(!RegexUtils.checkEmail(username)){
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, LoginEnum.EMAIL_ERROR.getSeq(), LoginEnum.EMAIL_ERROR.getDesc(),null);
		}
		if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, ParameterEnum.PARAMETER_NULL.getSeq(), ParameterEnum.PARAMETER_NULL.getDesc(),null);
		}
		password = RSAUtil.decPassWord(password);
		if(password.length() < 6) {
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, LoginEnum.PASSWORD_LENGTH_ERROR.getSeq(), LoginEnum.PASSWORD_LENGTH_ERROR.getDesc(),null);
		}
		return loginService.login(request, username, password);
	}

	@PostMapping("/v2/login")
	@ApiOperation(value="免加密登录", notes="免加密用户登录")
	public Response<Object> v2Login(HttpServletRequest request,
								  @ApiParam(value = "用户名", required = true) @RequestParam String username,
								  @ApiParam(value = "用户名", required = true) @RequestParam String password)
			throws UnknownHostException {
		logger.info("v2Login clientIp is: {} ,username: {}", IpUtil.getClientIp(request), username);
		logger.info("v2Login serverIp is: {}", IpUtil.getCurrentIp());
		if(!RegexUtils.checkEmail(username)){
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, LoginEnum.EMAIL_ERROR.getSeq(), LoginEnum.EMAIL_ERROR.getDesc(),null);
		}
		if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, ParameterEnum.PARAMETER_NULL.getSeq(), ParameterEnum.PARAMETER_NULL.getDesc(),null);
		}
		if(password.length() < 6) {
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, LoginEnum.PASSWORD_LENGTH_ERROR.getSeq(), LoginEnum.PASSWORD_LENGTH_ERROR.getDesc(), null);
		}
		return loginService.login(request, username, password);
	}
	
	@PostMapping("/logOut")
	@ApiOperation(value="退出", notes="用户登录退出")
	public Response<Object> loginOut(HttpServletRequest request) {
		String token = request.getHeader("token");
		String bitaToken = request.getHeader("bitaToken");
		logger.debug("pai token: {}, bitaToken: {}", token, bitaToken);
		Jedis jedis = null;
		try {
			JedisPool jedisPool = redisCacheConfig.getJedisPool();
			jedis = jedisPool.getResource();
			logger.debug("business service get redisResource success");
			String bitaKey = env.getPrefix() + bitaToken;
			String paiKey = env.getPrefix() + token;
			jedis.del(bitaKey);
			jedis.del(paiKey);
			request.getSession().invalidate();
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, LoginEnum.LOGOUT_SUCCESS.getSeq(), LoginEnum.LOGOUT_SUCCESS.getDesc(), null);
		} catch (Exception e) {
			logger.error("get redisResource failed");
			logger.error(e.getMessage(), e);
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, LoginEnum.LOGOUT_FAILED.getSeq(), LoginEnum.LOGOUT_FAILED.getDesc(), null);
		} finally {
			if (jedis != null) {
				jedis.close();
			}
		}
	}

	@GetMapping("/checkToken")
	@ApiOperation(value="验证用户token是否有效", notes="验证用户token是否有效")
	public Response<Void> checkToken() {
		logger.info("interceptor already check user token");
		return Response.ok();
	}
}
